import {useState, useEffect, useRef } from 'react'
import { Sku, Toast } from 'react-vant';
import {useNavigate} from 'react-router-dom'

const customStepperConfig = {
    quotaText: '单次限购100件',
    stockFormatter: (stock) => `剩余${stock}`,
    handleOverLimit: (data) => {
      const { action, limitType, quota, startSaleNum = 1 } = data;
      if (action === 'minus') {
        Toast(startSaleNum > 1 ? `${startSaleNum}件起售` : '至少选择一件商品');
      } else if (action === 'plus') {
        if (limitType === 0) {
          Toast(`限购${quota}件`);
        } else {
          Toast('库存不够了');
        }
      }
    },
  };

const ProductSku = ({ id, onShow, skuDate, flag}) => {
    const navigate = useNavigate()
    const ref = useRef(null)
    const onShowSku = () => {
        onShow(ref)
    }
    useEffect(() => {
        flag&&onShowSku()
    }, [flag])

    const onAddCart = async (value) => {
        let token = sessionStorage.getItem('token')
        if (token) {
          let product = skuDate[0]
          product.shopInfo = value
          let shop = JSON.parse(localStorage.getItem('shop')) || []
          let flag = shop.indexOf(item => item.id === product.id)
          flag === -1 ? shop.push(product) : shop[flag] = product
          localStorage.setItem('shop', JSON.stringify(shop))
            navigate('/shop')
        } else {
            navigate('/login')
        }
    } 
    return (
        <div>
            {skuDate && skuDate.map(item => {
                let demoData = item.getSkuData
                item.getSkuData.goods_id = item.id
                item.getSkuData.goods_info.price = item.price
                return (
                    <Sku
                        key={item.id}
                        ref={ref}
                        sku={demoData.sku}
                        goods={demoData.goods_info}
                        goodsId={demoData.goods_id}
                        properties={demoData.properties}
                        quota={demoData.quota}
                        quotaUsed={demoData.quota_used}
                        startSaleNum={demoData.start_sale_num}
                        onBuyClicked={(r) => console.log(r)}
                        onStepperChange={(v) => console.log(v)}
                        onAddCart={(v)=> onAddCart(v)}
                        customStepperConfig={customStepperConfig}
                    />
                )
            })}
        </div>
    )
}

export default ProductSku